 package implementation.gambiarra;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import started.ClientProperties;
import entility.Job;
import entility.JobImpl;
import entility.Machine;
import entility.Notification;

public class SendFiles extends Thread{

	private Machine mac;
	private File file;
	
	public boolean isWorking;
	
	
	public ClientProperties props =ClientProperties.getInstance();

	public SendFiles(Machine mac, File file) {
		// TODO Auto-generated constructor stub
		this.mac = mac;
		this.file = file;
	}

	public SendFiles()
	{
		isWorking = false;
	}

	public Machine getMac() {
		return mac;
	}
	
	

	public void setMac(Machine mac) {
		this.mac = mac;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public void sendFiles() throws Exception{
		
		
		isWorking = true;
		int quantLines = props.getPackageSize();

		List<String> partialFile  = new ArrayList<String>();

		BufferedReader reader;
		String line = null;

		Job job = new JobImpl(Notification.CLIENT);
		job.setMethod("execute");


		reader = new BufferedReader(new FileReader(file));
		job.setHead("CLIENT");

		while ((line = reader.readLine()) != null) {
			partialFile.add(line);
			if(partialFile.size() > quantLines){
				job.setData(partialFile);

				mac.getMessage(job,10000);
				partialFile.clear();
			}
		}

		reader.close();

		if(partialFile.size() > 0){
			job.setData(partialFile);

			mac.getMessage(job,10000);				
			partialFile.clear();
		}
		isWorking = false;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			sendFiles();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("Erro SendFiles: IOException");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("Erro SendFiles: ClassNotFoundException");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
